package com.rightsidetech.http.controller.admin.export;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.utils.BeanValidator;
import com.rightsidetech.commom.utils.DateUtil;
import com.rightsidetech.commom.utils.ExportExcelUtils;
import com.rightsidetech.http.aspect.Auth;
import com.rightsidetech.http.aspect.Log;
import com.rightsidetech.http.base.BaseController;
import com.rightsidetech.mall.dto.log.request.MallLogPageReq;
import com.rightsidetech.mall.dto.log.response.MallLogPageResp;
import com.rightsidetech.mall.service.MallCommodityLogService;
import com.rightsidetech.system.dtos.request.BatteryCheckReq;
import com.rightsidetech.system.dtos.request.CompanyAreaReq;
import com.rightsidetech.system.dtos.request.FeedbackPageReq;
import com.rightsidetech.system.dtos.request.agent.AgentInfoReq;
import com.rightsidetech.system.dtos.request.store.StoreIntegralPageReq;
import com.rightsidetech.system.dtos.request.store.StoreIntegralRecordReq;
import com.rightsidetech.system.dtos.request.store.SysStoreInfoReq;
import com.rightsidetech.system.dtos.response.CompanyAreaResp;
import com.rightsidetech.system.dtos.response.FeedbackPageResp;
import com.rightsidetech.system.dtos.response.agent.AgentInfoResp;
import com.rightsidetech.system.dtos.response.store.StoreIntegralRecordResp;
import com.rightsidetech.system.dtos.response.store.StoreIntegralResp;
import com.rightsidetech.system.dtos.response.store.SysStoreInfoResp;
import com.rightsidetech.system.entity.SysBatteryCheck;
import com.rightsidetech.system.entity.SysUserLoginInfo;
import com.rightsidetech.system.service.*;
import com.rightsidetech.trade.dtos.request.*;
import com.rightsidetech.trade.dtos.request.integral.IntegralOperateRecordReq;
import com.rightsidetech.trade.dtos.response.*;
import com.rightsidetech.trade.dtos.response.integral.IntegralOperateRecordResp;
import com.rightsidetech.trade.service.TdCommodityUserOrderService;
import com.rightsidetech.trade.service.TdIntegralOrderService;
import com.rightsidetech.trade.service.TdStatisService;
import com.rightsidetech.user.dtos.requst.UserInfoReq;
import com.rightsidetech.user.dtos.response.UserInfoResp;
import com.rightsidetech.user.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shenyu.client.springmvc.annotation.ShenyuSpringMvcClient;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @Package: com.rightsidetech.http.controller.admin.export
 * @ClassName: ExportCommonController
 * @Author: yinj
 * @CreateTime: 2021/10/28 15:12
 * @Description: 导出接口相关
 */
@RestController
@RequestMapping("/admin/export")
@ShenyuSpringMvcClient(path = "/admin/export/**")
@Api(tags = "导出表格相关api")
public class AdminExportController extends BaseController {

    @Resource
    private UserInfoService userInfoService;
    @Resource
    private SysCompanyAreaService sysCompanyAreaService;
    @Resource
    private SysUserLoginInfoService sysUserLoginInfoService;

    @Resource
    private TdCommodityUserOrderService tdCommodityUserOrderService;
    @Resource
    private AgentInfoService agentInfoService;
    @Resource
    private SysStoreInfoService sysStoreInfoService;
    @Resource
    private MallCommodityLogService mallCommodityLogService;
    @Resource
    private SysFeedbackService sysFeedbackService;
    @Resource
    private SysStoreIntegralService sysStoreIntegralService;
    @Resource
    private TdIntegralOrderService tdIntegralOrderService;
    @Resource
    private SysBatteryCheckService sysBatteryCheckService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private TdStatisService tdStatisService;

    @Log
    @GetMapping("/userInfo")
    @ApiOperation("用户信息导出")
    @Auth(bizType = Auth.OPERATOR)
    @ApiOperationSupport(ignoreParameters = {"pageNo", "pageSize"})
    public ResponseData exportUserInfo(UserInfoReq userInfoReq, String tokenAdmin) {
        List<UserInfoResp> list = userInfoService.exportList(userInfoReq);
        if (CollectionUtils.isEmpty(list)) {
            return new ResponseData(CodeIdEnum.EMPTY_DATA.getValue(), "数据为空，无法导出");
        }
        if (list.size() > 30000) {
            return new ResponseData(CodeIdEnum.LIST_MAX);
        }
        List<Object[]> dataList = new ArrayList<Object[]>();
        String[] rowsName = new String[]{"会员号", "昵称", "手机号", "账号", "等级名称", "账号状态", "注册时间"};
        for (UserInfoResp resp : list) {

            Object[] obj = new Object[7];
            obj[0] = resp.getMemberNo();
            obj[1] = resp.getPetName();
            obj[2] = resp.getPhoneNo();
            obj[3] = resp.getLoginName();
            obj[4] = resp.getLevelName();
            if (!StringUtils.isEmpty(resp.getStatus())) {
                obj[5] = resp.getStatus() == 0 ? "正常" : "拉黑";
            } else {
                obj[5] = "";
            }

            obj[6] = DateUtil.getDate(resp.getCreatedAt(), "yyyy-MM-dd HH:mm:ss");

            dataList.add(obj);
        }
        String title = "用户信息" + DateUtil.getDate(DateUtil.datePattern);
        ExportExcelUtils ex = new ExportExcelUtils(title, rowsName, dataList, resp);
        ex.exportData();
        return null;
    }

    @Log
    @GetMapping("/companyArea")
    @ApiOperation("大区信息导出")
    @Auth(bizType = Auth.OPERATOR)
    @ApiOperationSupport(ignoreParameters = {"pageNo", "pageSize"})
    public ResponseData exportCompanyArea(CompanyAreaReq req, String tokenAdmin) {
        List<CompanyAreaResp> list = sysCompanyAreaService.exList(req);
        if (CollectionUtils.isEmpty(list)) {
            return new ResponseData(CodeIdEnum.EMPTY_DATA.getValue(), "数据为空，无法导出");
        }
        if (list.size() > 30000) {
            return new ResponseData(CodeIdEnum.LIST_MAX);
        }
        List<Object[]> dataList = new ArrayList<Object[]>();
        String[] rowsName = new String[]{"大区名称", "负责人", "手机号", "创建人", "创建时间", "状态"};
        for (CompanyAreaResp resp : list) {

            Object[] obj = new Object[6];
            obj[0] = resp.getName();
            obj[1] = resp.getPrincipalName();
            obj[2] = resp.getMobileNo();
            obj[3] = resp.getCreaterName();
            obj[4] = DateUtil.getDate(resp.getCreaterAt(), "yyyy-MM-dd HH:mm:ss");

            if (resp.getStatus() != null) {
                obj[5] = resp.getStatus() == 1 ? "营业中" : "已关闭";
            } else {
                obj[5] = "";
            }

            dataList.add(obj);
        }
        String title = "大区列表" + DateUtil.getDate(DateUtil.datePattern);
        ExportExcelUtils ex = new ExportExcelUtils(title, rowsName, dataList, resp);
        ex.exportData();
        return null;
    }


    @Log
    @GetMapping("/order")
    @ApiOperation("订单信息导出")
    @Auth(bizType = Auth.OPERATOR)
    @ApiOperationSupport(ignoreParameters = {"pageNo", "pageSize"})
    public ResponseData exportTdCommodity(TdCommodityOrderListRequest req, String tokenAdmin) {
        Long loginInfoId = sysUserService.sysUsercheckToken(tokenAdmin);
        SysUserLoginInfo loginInfo = sysUserLoginInfoService.selectByLoginInfo(loginInfoId);
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        if(loginInfo.getSysCompanyAreaId() != 0){
            req.setAreaId(loginInfo.getSysCompanyAreaId());
        }

        List<TdCommodityUserOrderResp> list = tdCommodityUserOrderService.selectList(req);
        if (CollectionUtils.isEmpty(list)) {
            return new ResponseData(CodeIdEnum.EMPTY_DATA.getValue(), "数据为空，无法导出");
        }
        if (list.size() > 30000) {
            return new ResponseData(CodeIdEnum.LIST_MAX);
        }
        List<Object[]> dataList = new ArrayList<Object[]>();
        String[] rowsName = new String[]{"订单编号", "联系人", "总金额（元）", "优惠金额（元）", "实付金额（元）", "所属门店", "所属代理商", "所属大区", "订单类型", "下单时间", "付款时间","来源", "订单状态","其他平台订单编号"};
        for (TdCommodityUserOrderResp resp : list) {

            Object[] obj = new Object[14];
            obj[0] = resp.getOrderNo();
            obj[1] = resp.getUsName();
            obj[2] = resp.getTotalAmount().divide(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP);
            obj[3] = resp.getDiscountAmount().divide(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP);
            obj[4] = resp.getActualAmount().divide(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP);
            obj[5] = resp.getStoreName();
            obj[6] = resp.getAgentName();
            obj[7] = resp.getAreaName();
            obj[8] = resp.getOrderType() == 0 ? "上门服务" : "到店自取";
            obj[9] = DateUtil.getDate(resp.getCreatedAt(), "yyyy-MM-dd HH:mm:ss");
            obj[10] = DateUtil.getDate(resp.getPayTime(), "yyyy-MM-dd HH:mm:ss");
            String source = "";
            //0-系统, 1-淘宝, 2-京东, 3-抖音,4-拼多多, 5-天猫, 6-苏宁
            switch (resp.getSource()) {
                case 0:
                    source = "系统";
                    break;
                case 1:
                    source = "淘宝";
                    break;
                case 2:
                    source = "京东";
                    break;
                case 3:
                    source = "抖音";
                    break;
                case 4:
                    source = "拼多多";
                    break;
                case 5:
                    source = "天猫";
                    break;
                case 6:
                    source = "苏宁";
                    break;
                default:
                    break;
            }
            obj[11] = source;
            String orderStatus = "";
            switch (resp.getOrderStatus()) {
                case 0:
                    orderStatus = "待付款";
                    break;
                case 1:
                    orderStatus = "待接单";
                    break;
                case 2:
                    orderStatus = "已完成";
                    break;
                case 3:
                    orderStatus = "售后";
                    break;
                case 4:
                    orderStatus = "退款";
                    break;
                case -1:
                    orderStatus = "取消订单";
                default:
                    break;
            }
            obj[12] = orderStatus;
            obj[13] = resp.getOtherPaltformsOrderNo();
            dataList.add(obj);
        }
        String title = "订单列表" + DateUtil.getDate(DateUtil.datePattern);
        ExportExcelUtils ex = new ExportExcelUtils(title, rowsName, dataList, resp);
        ex.exportData();
        return null;
    }


    @Log
    @GetMapping("/agent")
    @ApiOperation("代理商信息导出")
    @Auth(bizType = Auth.OPERATOR)
    @ApiOperationSupport(ignoreParameters = {"pageNo", "pageSize"})
    public ResponseData exportAgentList(AgentInfoReq req, String tokenAdmin) {
        Long loginInfoId = sysUserService.sysUsercheckToken(tokenAdmin);
        SysUserLoginInfo loginInfo = sysUserLoginInfoService.selectByLoginInfo(loginInfoId);
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        if(loginInfo.getSysCompanyAreaId() != 0){
            req.setAreaId(loginInfo.getSysCompanyAreaId());
        }

        List<AgentInfoResp> list = agentInfoService.exportAgentList(req);
        if (CollectionUtils.isEmpty(list)) {
            return new ResponseData(CodeIdEnum.EMPTY_DATA.getValue(), "数据为空，无法导出");
        }
        if (list.size() > 30000) {
            return new ResponseData(CodeIdEnum.LIST_MAX);
        }
        List<Object[]> dataList = new ArrayList<Object[]>();
        String[] rowsName = new String[]{"代理商名称", "负责人", "手机号", "所属大区", "客服电话", "创建人", "创建时间", "状态"};
        for (AgentInfoResp resp : list) {

            Object[] obj = new Object[8];
            obj[0] = resp.getName();
            obj[1] = resp.getPrincipalName();
            obj[2] = resp.getMobileNo();
            obj[3] = resp.getAreaName();
            obj[4] = resp.getCustomerMobileNo();
            obj[5] = resp.getCreatedName();
            obj[6] = DateUtil.getDate(resp.getCreatedAt(), "yyyy-MM-dd HH:mm:ss");

            if (resp.getStatus() != null) {
                switch (resp.getStatus()) {
                    case 1:
                        obj[7] = "营业中";
                        break;
                    case -1:
                        obj[7] = "已关闭";
                        break;
                    default:
                        break;
                }
            }

            dataList.add(obj);
        }
        String title = "代理商列表" + DateUtil.getDate(DateUtil.datePattern);
        ExportExcelUtils ex = new ExportExcelUtils(title, rowsName, dataList, resp);
        ex.exportData();
        return null;
    }

    @Log
    @GetMapping("/store")
    @ApiOperation("门店信息导出")
    @Auth(bizType = Auth.OPERATOR)
    @ApiOperationSupport(ignoreParameters = {"pageNo", "pageSize"})
    public ResponseData exportStoreList(SysStoreInfoReq req, String tokenAdmin) {
        Long loginInfoId = sysUserService.sysUsercheckToken(tokenAdmin);
        SysUserLoginInfo loginInfo = sysUserLoginInfoService.selectByLoginInfo(loginInfoId);
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        if(loginInfo.getSysCompanyAreaId() != 0){
            req.setAreaId(loginInfo.getSysCompanyAreaId());
        }

        List<SysStoreInfoResp> list = sysStoreInfoService.exportStoreList(req);
        if (CollectionUtils.isEmpty(list)) {
            return new ResponseData(CodeIdEnum.EMPTY_DATA.getValue(), "数据为空，无法导出");
        }
        if (list.size() > 30000) {
            return new ResponseData(CodeIdEnum.LIST_MAX);
        }
        List<Object[]> dataList = new ArrayList<Object[]>();
        String[] rowsName = new String[]{"门店名称", "负责人", "手机号", "所属代理商", "门店等级", "地址", "积分", "状态"};
        for (SysStoreInfoResp resp : list) {

            Object[] obj = new Object[8];
            obj[0] = resp.getStoreName();
            obj[1] = resp.getStoreBoss();
            obj[2] = resp.getConnectWay();
            obj[3] = resp.getAgentName();
            obj[4] = resp.getGradeName();
            obj[5] = resp.getAdress();
//            BigDecimal point = BigDecimal.ZERO;
//            if (!StringUtils.isEmpty(resp.getPoint())){
//                point  = resp.getPoint();
//            }
//            obj[6] = point.setScale(0, BigDecimal.ROUND_DOWN ); // 向下取整
            if (resp.getStatus() != null) {
                switch (resp.getStatus()) {
                    case 1:
                        obj[6] = "营业中";
                        break;
                    case -1:
                        obj[6] = "已关闭";
                        break;
                    default:
                        break;
                }
            }

            dataList.add(obj);
        }
        String title = "门店列表" + DateUtil.getDate(DateUtil.datePattern);
        ExportExcelUtils ex = new ExportExcelUtils(title, rowsName, dataList, resp);
        ex.exportData();
        return null;
    }

    @Log
    @GetMapping("/mall_log")
    @ApiOperation("商品操作记录导出")
    @Auth(bizType = Auth.OPERATOR)
    @ApiOperationSupport(ignoreParameters = {"pageNo", "pageSize"})
    public ResponseData exportMallLogList(MallLogPageReq request, String tokenAdmin) {
        List<MallLogPageResp> result = mallCommodityLogService.selectList(request);
        if (CollUtil.isEmpty(result)) {
            return new ResponseData(CodeIdEnum.EMPTY_DATA.getValue(), "数据为空，无法导出");
        }
        if (result.size() > 30000) {
            return new ResponseData(CodeIdEnum.LIST_MAX);
        }
        List<Object[]> list = new ArrayList<>();
        String[] rowsName = new String[]{"商品名称", "商城", "操作", "详情", "操作人", "操作时间"};
        for (MallLogPageResp res : result) {
            Object[] objs = new Object[rowsName.length];
            objs[0] = res.getCommodityName();
            objs[1] = res.getCommodityMarketName();
            objs[2] = res.getOperate();
            objs[3] = res.getDetails();
            objs[4] = res.getLoginName();
            objs[5] = res.getCreatedAt();
            list.add(objs);
        }
        String title = "商品操作记录" + DateUtil.getDate(DateUtil.datePattern);
        ExportExcelUtils ex = new ExportExcelUtils(title, rowsName, list, resp);
        ex.exportData();
        return null;
    }

    @Log
    @GetMapping("/feedback")
    @ApiOperation("用户反馈记录导出")
    @Auth(bizType = Auth.OPERATOR)
    @ApiOperationSupport(ignoreParameters = {"pageNo", "pageSize"})
    public ResponseData exportFeedbackList(FeedbackPageReq req, String tokenAdmin) {
        List<FeedbackPageResp> resps = sysFeedbackService.selectList(req);
        if (CollUtil.isEmpty(resps)) {
            return new ResponseData(CodeIdEnum.EMPTY_DATA.getValue(), "数据为空，无法导出");
        }
        if (resps.size() > 30000) {
            return new ResponseData(CodeIdEnum.LIST_MAX);
        }
        List<Object[]> list = new ArrayList<>();
        String[] rowsName = new String[]{"订单编号", "姓名", "手机号", "反馈时间", "反馈问题", "描述", "状态", "回复内容"};
        for (FeedbackPageResp resp : resps) {
            Object[] objs = new Object[rowsName.length];
            objs[0] = resp.getOrderNo();
            objs[1] = resp.getUserName();
            objs[2] = resp.getPhoneNo();
            objs[3] = resp.getCreatedAt();
            objs[4] = resp.getQuestion();
            objs[5] = resp.getQuestionContent();
            if (resp.getStatus() != null) {
                switch (resp.getStatus()) {
                    case 0:
                        objs[6] = "待处理";
                        break;
                    case 1:
                        objs[6] = "已读";
                        break;
                    case 2:
                        objs[6] = "已回复";
                        break;
                    default:
                        break;
                }
            }
            objs[7] = resp.getReply();
            list.add(objs);
        }
        String title = "用户反馈记录" + DateUtil.getDate(DateUtil.datePattern);
        ExportExcelUtils ex = new ExportExcelUtils(title, rowsName, list, resp);
        ex.exportData();
        return null;
    }

    @Log
    @GetMapping("/integral_record")
    @ApiOperation("积分操作记录")
    @Auth(bizType = Auth.OPERATOR)
    @ApiOperationSupport(ignoreParameters = {"pageNo", "pageSize"})
    public ResponseData exportIntegralRecord(StoreIntegralRecordReq req, String tokenAdmin) {
        Long loginInfoId = sysUserService.sysUsercheckToken(tokenAdmin);
        SysUserLoginInfo loginInfo = sysUserLoginInfoService.selectByLoginInfo(loginInfoId);
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        if(loginInfo.getSysCompanyAreaId() != 0){
            req.setAreaId(loginInfo.getSysCompanyAreaId());
        }

        List<StoreIntegralRecordResp> resps = sysStoreIntegralService.selectList(req);
        if (CollUtil.isEmpty(resps)) {
            return new ResponseData(CodeIdEnum.EMPTY_DATA.getValue(), "数据为空，无法导出");
        }
        if (resps.size() > 30000) {
            return new ResponseData(CodeIdEnum.LIST_MAX);
        }
        String[] rowsName = new String[]{"门店名称", "操作", "备注", "操作人", "操作时间"};
        List<Object[]> list = new ArrayList<>();
        for (StoreIntegralRecordResp resp : resps) {
            Object[] objs = new Object[rowsName.length];
            objs[0] = resp.getStoreName();
            switch (resp.getOperateType()) {
                case 0: {
                    objs[1] = "商品售卖";
                    break;
                }
                case 1: {
                    objs[1] = "系统奖励";
                    break;
                }
                case 2: {
                    objs[1] = "签到奖励";
                    break;
                }
                case 3: {
                    objs[1] = "商品退货";
                    break;
                }
                case 4: {
                    objs[1] = "积分兑换";
                    break;
                }
            }
            objs[2] = resp.getRemark();
            objs[3] = resp.getOperateName();
            objs[4] = resp.getCreatedAt();
            list.add(objs);
        }
        String title = "积分操作记录" + DateUtil.getDate(DateUtil.datePattern);
        ExportExcelUtils ex = new ExportExcelUtils(title, rowsName, list, resp);
        ex.exportData();
        return null;
    }

    @Log
    @GetMapping("/store_integral")
    @ApiOperation("门店积分导出")
    @Auth(bizType = Auth.OPERATOR)
    @ApiOperationSupport(ignoreParameters = {"pageNo", "pageSize"})
    public ResponseData exportStoreIntegral(StoreIntegralPageReq req, String tokenAdmin) {
        Long loginInfoId = sysUserService.sysUsercheckToken(tokenAdmin);
        SysUserLoginInfo loginInfo = sysUserLoginInfoService.selectByLoginInfo(loginInfoId);
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        if(loginInfo.getSysCompanyAreaId() != 0){
            req.setAreaId(loginInfo.getSysCompanyAreaId());
        }

        List<StoreIntegralResp> resps = sysStoreIntegralService.selectIntegralList(req);
        if (CollUtil.isEmpty(resps)) {
            return new ResponseData(CodeIdEnum.EMPTY_DATA.getValue(), "数据为空，无法导出");
        }
        if (resps.size() > 30000) {
            return new ResponseData(CodeIdEnum.LIST_MAX);
        }
        String[] rowsName = new String[]{"门店名称", "总积分"};
        List<Object[]> list = new ArrayList<>();
        for (StoreIntegralResp resp : resps) {
            Object[] objs = new Object[rowsName.length];
            objs[0] = resp.getStoreName();
            objs[1] = resp.getPoint();
            list.add(objs);
        }
        String title = "门店积分" + DateUtil.getDate(DateUtil.datePattern);
        ExportExcelUtils ex = new ExportExcelUtils(title, rowsName, list, resp);
        ex.exportData();
        return null;
    }

    @Log
    @GetMapping("/orderBill")
    @ApiOperation("商城账单导出")
    @Auth(bizType = Auth.OPERATOR)
    @ApiOperationSupport(ignoreParameters = {"pageNo", "pageSize"})
    public ResponseData exportTdCommodityBill(TdCommodityTradeOrderReq req, String tokenAdmin) {
        req.setPageNo(1);
        req.setPageSize(15);
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }

        Long loginInfoId = sysUserService.sysUsercheckToken(tokenAdmin);
        SysUserLoginInfo loginInfo = sysUserLoginInfoService.selectByLoginInfo(loginInfoId);
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        if(loginInfo.getSysCompanyAreaId() != 0){
            req.setAreaId(loginInfo.getSysCompanyAreaId());
        }

        List<TdCommodityTradeOrderResp> list = tdCommodityUserOrderService.findCommodityBillList(req);
        if (CollectionUtils.isEmpty(list)) {
            return new ResponseData(CodeIdEnum.EMPTY_DATA.getValue(), "数据为空，无法导出");
        }
        if (list.size() > 30000) {
            return new ResponseData(CodeIdEnum.LIST_MAX);
        }
        List<Object[]> dataList = new ArrayList<Object[]>();
        String[] rowsName = new String[]{"订单编号", "支付单号","总金额（元）", "优惠金额（元）", "实付金额（元）","状态", "付款时间","退款时间"};
        for (TdCommodityTradeOrderResp resp : list) {

            Object[] obj = new Object[12];
            obj[0] = resp.getOrderNo();
            obj[1] = resp.getThirdOrderNo();
            obj[2] = resp.getAmount().divide(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP);
            obj[3] = resp.getDiscountAmount().divide(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP);
            obj[4] = resp.getActualAmount().divide(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP);
            obj[5] = resp.getOrderStatus() == 0 ? "已支付" : "退款";
            obj[6] = DateUtil.getDate(resp.getCreatedAt(), "yyyy-MM-dd HH:mm:ss");
            obj[7] = DateUtil.getDate(resp.getRefundTime(), "yyyy-MM-dd HH:mm:ss");
            dataList.add(obj);
        }
        String title = "商城账单" + DateUtil.getDate(DateUtil.datePattern);
        ExportExcelUtils ex = new ExportExcelUtils(title, rowsName, dataList, resp);
        ex.exportData();
        return null;
    }


    @Log
    @GetMapping("/integral_order")
    @ApiOperation("积分兑换记录导出")
    @Auth(bizType = Auth.OPERATOR)
    @ApiOperationSupport(ignoreParameters = {"pageNo", "pageSize"})
    public ResponseData exportTdIntegral(IntegralOperateRecordReq req, String tokenAdmin) {
        Long loginInfoId = sysUserService.sysUsercheckToken(tokenAdmin);
        SysUserLoginInfo loginInfo = sysUserLoginInfoService.selectByLoginInfo(loginInfoId);
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        if(loginInfo.getSysCompanyAreaId() != 0){
           req.setAreaId(loginInfo.getSysCompanyAreaId());
        }

        List<IntegralOperateRecordResp> resps = tdIntegralOrderService.operateRecordList(req);
        if (CollUtil.isEmpty(resps)) {
            return new ResponseData(CodeIdEnum.EMPTY_DATA.getValue(), "数据为空，无法导出");
        }
        if (resps.size() > 30000) {
            return new ResponseData(CodeIdEnum.LIST_MAX);
        }
        String[] rowsName = new String[]{"订单编号", "门店名称", "手机号", "所属代理商", "所属大区", "支付积分", "商品名称", "地址", "下单时间", "物流单号"};
        List<Object[]> list = new ArrayList<>();
        for (IntegralOperateRecordResp resp : resps) {
            Object[] objs = new Object[rowsName.length];
            objs[0] = resp.getOrderNo();
            objs[1] = resp.getStoreName();
            objs[2] = resp.getConnectWay();
            objs[3] = resp.getAgentName();
            objs[4] = resp.getAreaName();
            objs[5] = resp.getPrice();
            objs[6] = resp.getCommodityName();
            objs[7] = resp.getAddress();
            objs[8] = resp.getCreatedAt();
            objs[9] = ObjectUtil.isEmpty(resp.getLogisticsOrderNo()) ? "" : resp.getLogisticsOrderNo();
            list.add(objs);
        }
        String title = "积分兑换记录" + DateUtil.getDate(DateUtil.datePattern);
        ExportExcelUtils ex = new ExportExcelUtils(title, rowsName, list, resp);
        ex.exportData();
        return null;
    }

    @Log
    @ApiOperation("订单售后列表导出")
    @Auth(bizType = Auth.OPERATOR)
    @GetMapping("/afterService")
    @ApiOperationSupport(ignoreParameters = {"pageNo", "pageSize"})
    public ResponseData exportAfterService(TdCommodityAfterServiceReq req, String tokenAdmin) throws Exception {
        Long loginInfoId = sysUserService.sysUsercheckToken(tokenAdmin);
        SysUserLoginInfo loginInfo = sysUserLoginInfoService.selectByLoginInfo(loginInfoId);
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        if(loginInfo.getSysCompanyAreaId() != 0){
            req.setAreaId(loginInfo.getSysCompanyAreaId());
        }

        List<TdCommodityAfterPageResp> resps = tdCommodityUserOrderService.selectAfterServiceList(req);
        if (CollUtil.isEmpty(resps)) {
            return new ResponseData(CodeIdEnum.EMPTY_DATA.getValue(), "数据为空，无法导出");
        }
        if (resps.size() > 30000) {
            return new ResponseData(CodeIdEnum.LIST_MAX);
        }
        String[] rowsName = new String[]{"订单编号", "联系人", "手机号","门店名称","代理商名称","大区名称","申请时间","售后原因", "售后状态","审核人", "审核时间"};
        List<Object[]> list = new ArrayList<>();
        for (TdCommodityAfterPageResp resp : resps) {
            Object[] objs = new Object[rowsName.length];
            objs[0] = resp.getOrderNo();
            objs[1] = resp.getUsName();
            objs[2] = resp.getUsPhoneNo();
            objs[3] = resp.getStoreName();
            objs[4] = resp.getAgentName();
            objs[5] = resp.getAreaName();
            objs[6] = DateUtil.getDate(resp.getCreatedAt(), "yyyy-MM-dd HH:mm:ss");
            objs[7] = resp.getReason();
            //售后状态, 0-待审核, 1-已完成,  -1-拒绝， -2-取消申请
            objs[8] = resp.getStatus() == 0 ? "待审核" : (resp.getStatus() == 1 ? "已完成" : (resp.getStatus() == -1 ? "拒绝" : "取消申请"));
            objs[9] = resp.getStoreLoginName();
            objs[10] = DateUtil.getDate(resp.getCheckedAt(), "yyyy-MM-dd HH:mm:ss");
            list.add(objs);
        }
        String title = "售后申请记录" + DateUtil.getDate(DateUtil.datePattern);
        ExportExcelUtils ex = new ExportExcelUtils(title, rowsName, list, resp);
        ex.exportData();
        return null;
    }

    @Log
    @ApiOperation("订单售后退款导出")
    @Auth(bizType = Auth.OPERATOR)
    @GetMapping("/afterServiceMoney")
    @ApiOperationSupport(ignoreParameters = {"pageNo", "pageSize"})
    public ResponseData exportAfterServiceMoney(TdCommodityAfterServiceMoneyReq req, String tokenAdmin) throws Exception {
        Long loginInfoId = sysUserService.sysUsercheckToken(tokenAdmin);
        SysUserLoginInfo loginInfo = sysUserLoginInfoService.selectByLoginInfo(loginInfoId);
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        if(loginInfo.getSysCompanyAreaId() != 0){
            req.setAreaId(loginInfo.getSysCompanyAreaId());
        }

        List<TdCommodityAfterServiceMoneyResp> resps = tdCommodityUserOrderService.selectAfterServiceMoneyList(req);
        if (CollUtil.isEmpty(resps)) {
            return new ResponseData(CodeIdEnum.EMPTY_DATA.getValue(), "数据为空，无法导出");
        }
        if (resps.size() > 30000) {
            return new ResponseData(CodeIdEnum.LIST_MAX);
        }
        String[] rowsName = new String[]{"订单编号", "联系人", "退款总金额(元)","优惠金额(元)","实际退款(元)","门店名称","代理商名称","大区名称", "订单类型","退款时间"};
        List<Object[]> list = new ArrayList<>();
        for (TdCommodityAfterServiceMoneyResp resp : resps) {
            Object[] objs = new Object[rowsName.length];
            objs[0] = resp.getOrderNo();
            objs[1] = resp.getUsName();
            objs[2] = StringUtils.isEmpty(resp.getTotalAmount()) ? 0 : resp.getTotalAmount().divide(new BigDecimal(100));
            objs[3] = StringUtils.isEmpty(resp.getDiscountAmount()) ? 0 : resp.getDiscountAmount().divide(new BigDecimal(100));
            objs[4] = StringUtils.isEmpty(resp.getActualAmount()) ? 0 : resp.getActualAmount().divide(new BigDecimal(100));
            objs[5] = resp.getStoreName();
            objs[6] = resp.getAgentName();
            objs[7] = resp.getAreaName();
            //售后状态, 0-待审核, 1-已完成,  -1-拒绝， -2-取消申请
            objs[8] = resp.getOrderType() == 0 ? "上门服务" : "到店自取";
            objs[9] = DateUtil.getDate(resp.getUpdatedAt(), "yyyy-MM-dd HH:mm:ss");
            list.add(objs);
        }
        String title = "售后退款记录" + DateUtil.getDate(DateUtil.datePattern);
        ExportExcelUtils ex = new ExportExcelUtils(title, rowsName, list, resp);
        ex.exportData();
        return null;
    }


    @Log
    @ApiOperation("电池检测导出")
    @Auth(bizType = Auth.OPERATOR)
    @GetMapping("/batteryCheck")
    @ApiOperationSupport(ignoreParameters = {"pageNo", "pageSize"})
    public ResponseData exportBatteryCheck(BatteryCheckReq request,String tokenAdmin){

        Long loginInfoId = sysUserService.sysUsercheckToken(tokenAdmin);
        SysUserLoginInfo loginInfo = sysUserLoginInfoService.selectByLoginInfo(loginInfoId);
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        if(loginInfo.getSysCompanyAreaId() != 0){
            request.setAreaId(loginInfo.getSysCompanyAreaId());
        }

        List<SysBatteryCheck> resps = sysBatteryCheckService.selectList(request);
        if (CollUtil.isEmpty(resps)) {
            return new ResponseData(CodeIdEnum.EMPTY_DATA.getValue(), "数据为空，无法导出");
        }
        if (resps.size() > 30000) {
            return new ResponseData(CodeIdEnum.LIST_MAX);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String[] rowsName = new String[]{"门店", "检测代理商", "电池名称", "型号", "电池编码", "提交日期", "质保期","放电时间","检测结果","检测日期","状态"};
        List<Object[]> list = new ArrayList<>();
        for (SysBatteryCheck resp : resps) {
            Object[] objs = new Object[rowsName.length];
            objs[0] = resp.getStoreName();
            objs[1] = resp.getAgentName();
            objs[2] = resp.getBatteryName();
            objs[3] = resp.getSpecs();
            objs[4] = resp.getBatteryCode();
            objs[5] = sdf.format(resp.getCreatedAt());
            if(ObjectUtil.isNotEmpty(resp.getWarranty())){
                switch (resp.getWarranty()){
                    case 1 : {
                        objs[6] = "换新";
                        break;
                    }
                    case 2 : {
                        objs[6] = "换专";
                        break;
                    }
                    case 3 : {
                        objs[6] = "换维";
                        break;
                    }
                }
            }

            objs[7] = resp.getDischargeTime();
            if(ObjectUtil.isNotEmpty(resp.getCheckResult())){
                switch (resp.getCheckResult()){
                    case 1 : {
                        objs[8] = "电池正常";
                        break;
                    }
                    case 2 : {
                        objs[8] = "可以跟换";
                        break;
                    }
                }
            }
            objs[9] = ObjectUtil.isEmpty(resp.getCheckTime()) ? null : sdf.format(resp.getCheckTime());
            switch (resp.getStatus()){
                case 0 : {
                    objs[10] = "待处理";
                    break;
                }
                case 1 : {
                    objs[10] = "已完成";
                    break;
                }
            }
            list.add(objs);
        }
        String title = "电池检测" + DateUtil.getDate(DateUtil.datePattern);
        ExportExcelUtils ex = new ExportExcelUtils(title, rowsName, list, resp);
        ex.exportData();
        return null;
    }



    @Log
    @ApiOperation("用户销量报表 导出")
    @Auth(bizType = Auth.OPERATOR)
    @GetMapping("/orderSalesVolumeDayExport")
    @ApiOperationSupport(ignoreParameters = {"pageNo", "pageSize"})
    public ResponseData orderSalesVolumeDayStatisExport(TdOrderSalesVolumeDayStatisReq req, String tokenAdmin) throws Exception {

        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }

        Long loginInfoId = sysUserService.sysUsercheckToken(tokenAdmin);
        SysUserLoginInfo loginInfo = sysUserLoginInfoService.selectByLoginInfo(loginInfoId);
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        if(loginInfo.getSysCompanyAreaId() != 0){
            req.setAreaId(loginInfo.getSysCompanyAreaId());
        }

        List<TdOrderSalesVolumeDayStatisResp> resps = tdStatisService.orderSalesVolumeDayStatisList( req);
        if (CollUtil.isEmpty(resps)) {
            return new ResponseData(CodeIdEnum.EMPTY_DATA.getValue(), "数据为空，无法导出");
        }
        if (resps.size() > 30000) {
            return new ResponseData(CodeIdEnum.LIST_MAX);
        }
        String[] rowsName = new String[]{"时间", "商品销量(组)", "退货(组)","订单","退货订单"};
        List<Object[]> list = new ArrayList<>();
        for (TdOrderSalesVolumeDayStatisResp resp : resps) {
            Object[] objs = new Object[rowsName.length];
            objs[0] = resp.getStatisAt();
            objs[1] = resp.getSalesVolume();
            objs[2] = resp.getRefundSalesVolume();
            objs[3] = resp.getOrderCount();
            objs[4] = resp.getRefundOrderCount();
            list.add(objs);
        }
        String title = "销量报表" + DateUtil.getDate(DateUtil.datePattern);
        ExportExcelUtils ex = new ExportExcelUtils(title, rowsName, list, resp);
        ex.exportData();
        return null;
    }


    @Log
    @ApiOperation("用户财务报表导出")
    @Auth(bizType = Auth.OPERATOR)
    @GetMapping("/orderIncomeRefundDayExport")
    @ApiOperationSupport(ignoreParameters = {"pageNo", "pageSize"})
    public ResponseData orderIncomeRefundDayStatisExport(TdOrderSalesVolumeDayStatisReq req, String tokenAdmin) throws Exception {

        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }

        Long loginInfoId = sysUserService.sysUsercheckToken(tokenAdmin);
        SysUserLoginInfo loginInfo = sysUserLoginInfoService.selectByLoginInfo(loginInfoId);
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        if(loginInfo.getSysCompanyAreaId() != 0){
            req.setAreaId(loginInfo.getSysCompanyAreaId());
        }

        List<TdOrderIncomeRefundDayStatisResp> resps = tdStatisService.orderIncomeRefundDayStatisList( req);
        if (CollUtil.isEmpty(resps)) {
            return new ResponseData(CodeIdEnum.EMPTY_DATA.getValue(), "数据为空，无法导出");
        }
        if (resps.size() > 30000) {
            return new ResponseData(CodeIdEnum.LIST_MAX);
        }
        String[] rowsName = new String[]{"时间", "微信收入金额(元)","其他平台收入金额(元)", "微信退款金额(元)","其他平台退款金额(元)","总收入(元)","总退款(元)","总入账(元)"};
        List<Object[]> list = new ArrayList<>();
        for (TdOrderIncomeRefundDayStatisResp resp : resps) {
            Object[] objs = new Object[rowsName.length];
            objs[0] = DateUtil.getDate(resp.getStatisAt(), "yyyy-MM-dd HH:mm:ss");
            objs[1] = resp.getWxIncomeAmount();
            objs[2] = resp.getOtherIncomeAmount();
            objs[3] = resp.getWxRefundAmount();
            objs[4] = resp.getOtherRefundAmount();
            objs[5] = resp.getWxIncomeAmount().add(resp.getOtherIncomeAmount());
            objs[6] = resp.getWxRefundAmount().add(resp.getOtherRefundAmount());
            objs[7] = resp.getWxIncomeAmount().add(resp.getOtherIncomeAmount());
            list.add(objs);
        }
        String title = "财务报表" + DateUtil.getDate(DateUtil.datePattern);
        ExportExcelUtils ex = new ExportExcelUtils(title, rowsName, list, resp);
        ex.exportData();
        return null;
    }
}
